package com.cyw.baselibrary.view.recycleViewdecoration;

import android.graphics.Canvas;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

/**
 * Creator: tsung_lin
 * data: 16/10/21 下午4:15
 * Description:grid
 */

public class ItemGridDecoration extends RecyclerView.ItemDecoration {

    private int horizontalSpace;
    private int verticalSpace;

    private int mGridSize;

    private boolean mNeedLeftSpacing = false;

    public ItemGridDecoration(int horizontalSpace,int verticalSpace, int gridSize) {
        this.horizontalSpace = horizontalSpace;
        this.verticalSpace = verticalSpace;
        mGridSize = gridSize;
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        int frameWidth = (int) ((parent.getWidth() - (float) horizontalSpace * (mGridSize - 1)) / mGridSize);
        int padding = parent.getWidth() / mGridSize - frameWidth;
        RecyclerView.LayoutParams layoutParams = ((RecyclerView.LayoutParams) view.getLayoutParams());
        int itemPosition = layoutParams.getViewAdapterPosition();
//        LogUtils.e("kk",">>>"+itemPosition+">>>>"+parent.getLayoutManager().getItemCount());
//        if(itemPosition==3||itemPosition==4||itemPosition==5){
//
//            return;
//        }
        if (itemPosition < mGridSize) {
            outRect.top = 0;
        } else {
            outRect.top = verticalSpace;
        }
        if (itemPosition % mGridSize == 0) {
            outRect.left = 0;
            outRect.right = padding;
            mNeedLeftSpacing = true;
        } else if ((itemPosition + 1) % mGridSize == 0) {
            mNeedLeftSpacing = false;
            outRect.right = 0;
            outRect.left = padding;
        } else if (mNeedLeftSpacing) {
            mNeedLeftSpacing = false;
            outRect.left = horizontalSpace - padding;
            if ((itemPosition + 2) % mGridSize == 0) {
                outRect.right = horizontalSpace - padding;
            } else {
                outRect.right = horizontalSpace / 2;
            }
        } else if ((itemPosition + 2) % mGridSize == 0) {
            mNeedLeftSpacing = false;
            outRect.left = horizontalSpace / 2;
            outRect.right = horizontalSpace - padding;
        } else {
            mNeedLeftSpacing = false;
            outRect.left = horizontalSpace / 2;
            outRect.right = horizontalSpace / 2;
        }
//        outRect.bottom = 0;
    }

}